package org.zoomdev.zoom.common.caster;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public final class ClassExtract {
    private static final HashSet<Class<?>> blackListInterface = new HashSet<>(4);
    static {
        // Blacklisted interfaces
        blackListInterface.add(Serializable.class);
        blackListInterface.add(Cloneable.class);
        blackListInterface.add(Comparable.class);
    }

    /**
     * Extra class to array. Including self, super class, interfaces
     *
     * @param src
     * @return
     */
    public static List<Class<?>> extractClass(Class<?> src) {
        List<Class<?>> set = new ArrayList<>();

        extractClass(set, src);

        return set;
    }

    private static void extractClass(List<Class<?>> set, Class<?> src) {
        if (src == null) {
            return;
        }
        if (src.isInterface()) {
            extraInterface(set, src);
        } else {
            if (src == Object.class) {
                set.add(Object.class);
                return;
            }
            set.add(src);
            Class<?>[] interfaces = src.getInterfaces();
            for (Class<?> inter : interfaces) {
                extraInterface(set, inter);
            }
            extractClass(set, src.getSuperclass());

        }

    }

    private static void extraInterface(List<Class<?>> set, Class<?> src) {
        if (blackListInterface.contains(src)) {
            return;
        }
        set.add(src);
        src = src.getSuperclass();
        if (src == null)
            return;
        extraInterface(set, src);
    }
}
